<script setup lang="ts">
import CategoryApi, { CategoryVo } from '@/api/category'
import { ref, onMounted, computed, onUnmounted } from 'vue'

import { useRoute } from 'vue-router'
import { useUserStore } from '@/store/modules/user'
import { useAuthStore } from '@/store/modules/auth'
import { ElMessageBox } from 'element-plus'
import {
  House,
  Folder,
  Star,
  Link,
  User,
  SwitchButton,
  ChatDotRound,
} from '@element-plus/icons-vue'
import { friendlyTime } from '@/utils/friendlyTime'

const userStore = useUserStore()
const authStore = useAuthStore()
const router = useRouter()
const route = useRoute()

const activeIndex = ref('/')
const classListObj = ref<CategoryVo[]>([])
const greetingText = ref('')
const showCursor = ref(true)
const isSticky = ref(false)
const activeCategoryId = ref<number | null>(null)
const wellKnownSaying = friendlyTime()

const hasLogin = computed(() => userStore.userInfo != undefined)
const userInfo = computed(() => userStore.userInfo)
const fullText = computed(() => `Hi, ${userInfo.value?.nickName}`)

const isMobile = ref(false)
const isMenuVisible = ref(false)

onMounted(() => {
  initData()
  typeText()
  window.addEventListener('scroll', handleScroll)
  // 根据当前路由设置激活状态
  setActiveByRoute()
  checkMobile()
  window.addEventListener('resize', checkMobile)
})

onUnmounted(() => {
  window.removeEventListener('resize', checkMobile)
})

const handleScroll = () => {
  isSticky.value = window.scrollY > 0
}

async function initData() {
  try {
    const { code, items } = await CategoryApi.getCategoryList()
    if (code === 200) {
      classListObj.value = items ?? []
    }
  } catch (error) {
    console.error('Failed to fetch categories:', error)
  }
}

const typeText = () => {
  let index = 0
  const timer = setInterval(() => {
    if (index < fullText.value.length) {
      greetingText.value += fullText.value[index]
      index++
    } else {
      clearInterval(timer)
      // wellKnownSaying.value = friendlyTime() ?? ''
      showCursor.value = false
    }
  }, 150)
}

const login = () => {
  router.push('/login')
}

const register = () => {
  router.push('/login')
}

const logout = async () => {
  await ElMessageBox.confirm('确定要退出登录吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
  try {
    await authStore.logout()
    ElMessage.success('退出登录成功')
    router.push('/login')
  } catch (error) {
    console.error('Failed to logout:', error)
  }
}

const handleCategoryClick = (categoryId: number) => {
  console.log('test2')
  activeCategoryId.value = categoryId
  activeIndex.value = '/share?classId=' + categoryId
  router.push(activeIndex.value)
}

const setActiveByRoute = () => {
  const path = route.path
  if (path.includes('/share')) {
    // 获取classId
    const categoryId = route.query.classId as any
    activeCategoryId.value = categoryId
    activeIndex.value = '/share?classId=' + categoryId
    return
  }
  activeIndex.value = path
  if (path.includes('/share') && route.query.classId) {
    activeCategoryId.value = Number(route.query.classId)
  } else {
    activeCategoryId.value = null
  }
}

// 监听路由变化
watch(
  () => route.fullPath,
  () => {
    setActiveByRoute()
  },
  { immediate: true }
)

const checkMobile = () => {
  isMobile.value = window.innerWidth <= 768
  if (!isMobile.value) {
    isMenuVisible.value = true
  }
}
</script>

<template>
  <nav class="navbar navbar-expand-lg fixed-top">
    <div class="container">
      <!-- 移动端菜单按钮 -->
      <button
        class="navbar-toggler"
        type="button"
        data-bs-toggle="collapse"
        data-bs-target="#navbarContent"
        aria-controls="navbarContent"
        aria-expanded="false"
        aria-label="Toggle navigation"
        style="background-color: #e5e5e5">
        <span class="navbar-toggler-icon"></span>
      </button>

      <!-- 导航内容 -->
      <div id="navbarContent" class="collapse navbar-collapse">
        <!-- 左侧菜单 -->
        <ul class="navbar-nav me-auto">
          <li class="nav-item">
            <router-link
              class="nav-link"
              to="/"
              :class="{ active: activeIndex === '/dashboard' }">
              <el-icon class="menu-icon"><House /></el-icon>
              <span>首页</span>
            </router-link>
          </li>

          <!-- 分类下拉菜单 -->
          <li class="nav-item dropdown">
            <a
              class="nav-link dropdown-toggle"
              :class="{ active: activeIndex.includes('/share') }"
              href="#"
              role="button"
              data-bs-toggle="dropdown"
              aria-expanded="false">
              <el-icon class="menu-icon"><Folder /></el-icon>
              <span>分类</span>
            </a>
            <ul class="dropdown-menu">
              <li v-for="item in classListObj" :key="item.id">
                <a
                  class="dropdown-item"
                  href="#"
                  :class="{ active: activeCategoryId === item.id }"
                  @click.prevent="handleCategoryClick(item.id ?? 0)">
                  {{ item.name }}
                </a>
              </li>
            </ul>
          </li>

          <li class="nav-item">
            <router-link
              class="nav-link"
              to="/appreciation"
              :class="{ active: activeIndex === '/appreciation' }">
              <el-icon class="menu-icon"><Star /></el-icon>
              <span>赞赏支持</span>
            </router-link>
          </li>

          <li class="nav-item">
            <router-link
              class="nav-link"
              to="/friend_links"
              :class="{ active: activeIndex === '/friend_links' }">
              <el-icon class="menu-icon"><Link /></el-icon>
              <span>友情链接</span>
            </router-link>
          </li>

          <li class="nav-item">
            <router-link
              class="nav-link"
              to="/chat"
              :class="{ active: activeIndex === '/chat' }">
              <el-icon class="menu-icon"><ChatDotRound /></el-icon>
              <span>deepseek</span>
            </router-link>
          </li>
        </ul>

        <!-- 右侧用户区域 -->
        <!-- TODO  后期实现搜索功能 -->
        <!-- <form class="d-flex" role="search">
          <input
            class="form-control me-2"
            type="search"
            placeholder="Search"
            aria-label="Search" />
          <button class="btn btn-outline-success" type="submit">Search</button>
        </form> -->
        <ul class="navbar-nav">
          <template v-if="!hasLogin">
            <li class="nav-item">
              <button class="btn btn-primary btn-sm me-2" @click="login">
                登录
              </button>
            </li>
            <li class="nav-item">
              <button class="btn btn-outline-primary btn-sm" @click="register">
                注册
              </button>
            </li>
          </template>

          <template v-else>
            <li class="nav-item dropdown">
              <a
                class="nav-link dropdown-toggle user-menu"
                href="#"
                role="button"
                data-bs-toggle="dropdown"
                aria-expanded="false">
                <img
                  :src="userInfo?.avatar"
                  class="user-avatar"
                  :alt="userInfo?.nickName" />
                <span class="user-name">{{ userInfo?.nickName }}</span>
              </a>
              <ul class="dropdown-menu dropdown-menu-end">
                <li>
                  <router-link class="dropdown-item" to="/user_info">
                    <el-icon><User /></el-icon>
                    <span>个人中心</span>
                  </router-link>
                </li>
                <li>
                  <hr class="dropdown-divider" />
                </li>
                <li>
                  <a class="dropdown-item" href="#" @click.prevent="logout">
                    <el-icon><SwitchButton /></el-icon>
                    <span>退出登录</span>
                  </a>
                </li>
              </ul>
            </li>
          </template>
        </ul>
      </div>
    </div>
  </nav>

  <!--   将背景图片展示全部-->
  <div class="hero-section">
    <div class="hero-content">
      <div class="greeting">
        <span class="greeting-text">
          <span class="greeting-gradient">{{ greetingText }}</span>
          <span v-if="showCursor" class="cursor">|</span>
        </span>
      </div>
      <div class="profile-info">
        <img :src="userInfo?.avatar" alt="Profile" class="profile-image" />
        <h2 class="profile-motto" :class="{ 'fade-in': wellKnownSaying }">
          <span class="gradient-text typing">{{ wellKnownSaying }}</span>
        </h2>
      </div>
    </div>
  </div>
</template>

<style lang="scss" scoped>
.navbar {
  background: linear-gradient(
    to right,
    rgba(45, 45, 45, 0.2),
    // 降低不透明度到 0.2
    rgba(45, 45, 45, 0.15) // 降低不透明度到 0.15
  );
  backdrop-filter: blur(5px); // 减小模糊程度从 8px 到 5px
  -webkit-backdrop-filter: blur(5px); // Safari 支持
  border-bottom: 1px solid rgba(255, 255, 255, 0.1); // 添加微妙的边框
  padding: 0.5rem 0;

  .nav-link {
    font-size: 1.2rem;
    font-weight: 500;
    padding: 0.5rem 1.2rem;
    transition: color 0.3s ease;
    color: #e5e5e5;
    display: flex;
    align-items: center;
    gap: 0.5rem;

    &:hover,
    &.active {
      color: #ffd700 !important;
    }

    i {
      font-size: 1rem;
    }
  }

  .dropdown-menu {
    background: rgba(45, 45, 45, 0.2);
    backdrop-filter: blur(5px);
    -webkit-backdrop-filter: blur(5px);
    border: 1px solid rgba(255, 255, 255, 0.1);

    .dropdown-item {
      color: #e5e5e5;
      display: flex;
      align-items: center;
      gap: 0.5rem;
      padding: 0.5rem 1rem;

      &:hover,
      &.active {
        background: rgba(255, 255, 255, 0.1);
        color: #ffd700 !important;
      }
    }

    .dropdown-divider {
      border-color: rgba(255, 255, 255, 0.1);
    }
  }

  .user-menu {
    display: flex;
    align-items: center;
    gap: 0.5rem;
  }

  .user-avatar {
    width: 32px;
    height: 32px;
    border-radius: 50%;
    object-fit: cover;
  }

  .user-name {
    color: #e5e5e5;
  }

  .btn {
    padding: 0.375rem 1rem;

    &.btn-primary {
      background: var(--el-color-primary);
      border-color: var(--el-color-primary);

      &:hover {
        background: var(--el-color-primary-dark-2);
        border-color: var(--el-color-primary-dark-2);
      }
    }

    &.btn-outline-primary {
      color: var(--el-color-primary);
      border-color: var(--el-color-primary);

      &:hover {
        background: var(--el-color-primary);
        border-color: var(--el-color-primary);
        color: white;
      }
    }
  }
}

// 针对不同屏幕尺寸优化字体大小
@media (min-width: 1200px) {
  // 大屏幕
  .navbar {
    .nav-link {
      font-size: 1.3rem; // 在大屏幕上更大 (约 20.8px)
    }
  }
}

@media (max-width: 991.98px) {
  // 移动端保持原来的大小
  .navbar {
    .nav-link {
      font-size: 1rem; // 移动端默认大小
    }
  }
  .navbar-collapse {
    background: rgba(45, 45, 45, 0.2);
    backdrop-filter: blur(5px);
    -webkit-backdrop-filter: blur(5px);
  }
}

.hero-section {
  // height: 200px;
  width: 100%;
  background-image: url('https://cdn.seovx.com/d/?mom=302');
  background-size: cover !important;
  background-position: center !important;
  background-repeat: no-repeat !important;
  position: relative;
  //margin-top: 50px; // 添加顶部边距，避免被导航栏遮挡
  overflow: hidden; // 防止内容溢出
  aspect-ratio: 4/3;
}

.hero-content {
  position: absolute;
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  background: rgba(0, 0, 0, 0.5);
  color: white;
}

.greeting {
  margin-bottom: 30px;
}

.greeting-text {
  font-size: 48px;
  font-weight: bold;
  text-shadow: 2px 2px 4px rgba(0, 0, 0, 0.5);

  .greeting-gradient {
    background: linear-gradient(
      45deg,
      #ffd700,
      // 金色
      #ff69b4,
      // 粉红
      #87ceeb,
      // 天蓝
      #98fb98 // 浅绿
    );
    background-size: 300% 300%;
    -webkit-background-clip: text;
    background-clip: text;
    color: transparent;
    animation: greeting-gradient 6s ease infinite;
  }
}

.cursor {
  animation: blink 1s infinite;
  color: #ffd700; // 光标颜色设置为金色
}

@keyframes greeting-gradient {
  0% {
    background-position: 0% 50%;
  }
  50% {
    background-position: 100% 50%;
  }
  100% {
    background-position: 0% 50%;
  }
}

@keyframes blink {
  0%,
  100% {
    opacity: 1;
  }
  50% {
    opacity: 0;
  }
}

.profile-info {
  text-align: center;
}

.profile-image {
  width: 120px;
  height: 120px;
  border-radius: 50%;
  border: 4px solid white;
  margin-bottom: 20px;
  transition: transform 0.3s ease;
}

.profile-image:hover {
  animation: spin 2s linear infinite;
  animation-timing-function: cubic-bezier(0.4, 0, 0.2, 1);
}

@keyframes spin {
  0% {
    transform: rotate(0deg);
  }
  100% {
    transform: rotate(360deg);
  }
}

.profile-motto {
  font-size: 24px;
  font-weight: normal;
  text-shadow: 1px 1px 2px rgba(0, 0, 0, 0.5);
  opacity: 0;
  transition: opacity 1s ease-in;

  &.fade-in {
    opacity: 1;
  }

  .gradient-text {
    background: linear-gradient(
      45deg,
      #ff6b6b,
      #4ecdc4,
      #45b7d1,
      #96c93d,
      #ff6b6b
    );
    background-size: 400% 400%;
    -webkit-background-clip: text;
    background-clip: text;
    color: transparent;
    animation: gradient 15s ease infinite, typing 3s steps(40, end);
    display: inline-block;
    white-space: nowrap;
    overflow: hidden;
    border-right: 2px solid transparent;
  }
}

@keyframes gradient {
  0% {
    background-position: 0% 50%;
  }
  50% {
    background-position: 100% 50%;
  }
  100% {
    background-position: 0% 50%;
  }
}

@keyframes typing {
  from {
    width: 0;
  }
  to {
    width: 100%;
  }
}

// 添加悬停效果
.gradient-text:hover {
  animation: gradient 3s ease infinite;
  transform: scale(1.05);
  transition: transform 0.3s ease;
  text-shadow: 0 0 8px rgba(255, 255, 255, 0.3);
}
</style>
